package org.star.dolphin.service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

@Service
public class ExcelService {

    /**
     * real excel
     *
     * @param in
     * @param fields
     * @return
     * @throws IOException
     * @throws RuntimeException
     */
    public List<Map<String, Object>> readExcel(InputStream in, List<String> fields) throws IOException, RuntimeException {
        List<Map<String, Object>> data = Lists.newArrayList();
        Workbook wb = WorkbookFactory.create(in);

        Integer sheetCount = wb.getNumberOfSheets();
        if (!sheetCount.equals(1)) {
            throw new RuntimeException("请检查Excel Sheet页");
        }

        //获取第一个sheet
        Sheet sheet = wb.getSheetAt(0);

        Integer count = 0;
        for (Row row : sheet) {
            //跳过第一行
            if (count.equals(0)) {
                count++;
                continue;
            }

            //如果当前行没有数据 跳出
            if (StringUtils.isBlank(row.getCell(0).toString())) {
                break;
            }

            Map<String, Object> rowData = Maps.newHashMap();
            //将excel数据解析后与field对应
            Integer cellIndex = 0;
            for (String field : fields) {
                Object value = null;
                Cell cell = row.getCell(cellIndex);
                if (ObjectUtils.allNotNull(cell)) {
                    value = getValue(cell);
                }

                rowData.put(field, value);

                cellIndex++;
            }

            data.add(rowData);
            count++;
        }

        return data;
    }

    /**
     * get row cell value
     *
     * @param cell
     * @return
     */
    private static Object getValue(Cell cell) {
        Object obj = null;
        switch (cell.getCellType()) {
            case BOOLEAN:
                obj = cell.getBooleanCellValue();
                break;
            case ERROR:
                obj = cell.getErrorCellValue();
                break;
            case NUMERIC:
                //obj = cell.getNumericCellValue();
                cell.setCellType(CellType.STRING);
                obj = cell.getStringCellValue();
                break;
            case STRING:
                obj = cell.getStringCellValue();
                break;
            default:
                break;
        }
        return obj;
    }

}
